package com.wnxy.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnxy.portal.common.constant.RedisConstant;
import com.wnxy.portal.entity.Booktype;
import com.wnxy.portal.mapper.BooktypeMapper;
import com.wnxy.portal.model.vo.BooktypeVo;
import com.wnxy.portal.service.IBooktypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Jet
 * @since 2023-12-11
 */
@Service
public class BooktypeServiceImpl extends ServiceImpl<BooktypeMapper, Booktype> implements IBooktypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<BooktypeVo> findBookTypes() {
        // 先从Redis中获取数据，如果没有获取到，就查询db后放入redis
        if (!redisTemplate.hasKey(RedisConstant.BOOK_TYPE_LIST)) {
            // 构造条件：指定查询的列
            QueryWrapper<Booktype> wrapper = new QueryWrapper();
            wrapper.select("id", "name");
            List<Booktype> list = baseMapper.selectList(wrapper);
            List<BooktypeVo> voList = list.stream().map(booktype -> new BooktypeVo(booktype.getId(), booktype.getName())).collect(Collectors.toList());
            // 查询的结果放入Redis
            redisTemplate.opsForList().rightPushAll(RedisConstant.BOOK_TYPE_LIST, voList);
            return voList;
        }
        // 如果Redis中已经有数据，直接查询Redis
        List result = redisTemplate.opsForList().range(RedisConstant.BOOK_TYPE_LIST, 0, -1);
        return result;
    }
}
